// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------
// Modification history:
// feature: Unified Transport Abstraction Layer Unified Transport Abstraction Layer
// feature: support multiple sending based on topic
// feature: In the case of white list configuration, only the same network segment is supported to send packets
// ------------------------------------------------------------------

#ifndef SRC_CPP_RTPS_TRANSPORT_UDPSENDERRESOURCE_HPP_
#define SRC_CPP_RTPS_TRANSPORT_UDPSENDERRESOURCE_HPP_

#include <ertps/utils/LocatorAlias.h>

#include <transport/SenderResource.h>

#include "UDPTransportInterface.h"

namespace vbs {
namespace transport {

class UDPSenderResource : public vbs::transport::SenderResource {
 public:
#ifdef EDDS_XDP_TRANSPORT_COMPILE
    UDPSenderResource(UDPTransportInterface& transport, vbsUDPSocket& socket, LixdpSocket* lixdp_socket,
                      unsigned int mask_len = 0, bool only_multicast_purpose = false, bool whitelisted = false,
                      uint32_t order = 65535)
#else
    UDPSenderResource(UDPTransportInterface& transport, vbsUDPSocket& socket, unsigned int mask_len = 0,
                      bool only_multicast_purpose = false, bool whitelisted = false, uint32_t order = 65535)
#endif
        : SenderResource(transport.kind()),
          socket_(std::move(socket)),
#ifdef EDDS_XDP_TRANSPORT_COMPILE
          lixdp_socket_(lixdp_socket),
          socket_type_(SocketType::SOCKET_TYPE_UDP),
#endif
          only_multicast_purpose_(only_multicast_purpose),
          whitelisted_(whitelisted),
          mask_len_(mask_len),
          transport_(transport) {
#ifdef EDDS_XDP_TRANSPORT_COMPILE
        if (lixdp_socket_ && transport.get_socket_type() == SocketType::SOCKET_TYPE_XDP) {
            // Implementation functions are bound to the right transport parameters
            clean_up = [this, &transport]() {
                transport.CloseOutputChannel(lixdp_socket_);
            };
            send_lambda_ = [this, &transport](unsigned char* data, uint32_t dataSize,
                                              vbsutil::xmlparser::LocatorsIterator* destination_locators_begin,
                                              vbsutil::xmlparser::LocatorsIterator* destination_locators_end) -> bool {
                return transport.send(data, dataSize, lixdp_socket_, destination_locators_begin,
                                      destination_locators_end, only_multicast_purpose_, whitelisted_, mask_len_);
            };
            socket_type_ = SocketType::SOCKET_TYPE_XDP;
        } else
#endif
        {
            // Implementation functions are bound to the right transport parameters
            clean_up = [this, &transport]() {
                transport.CloseOutputChannel(socket_);
            };
            local_address_ = socket_.local_endpoint().address();
            send_lambda_ = [this, &transport](unsigned char* data, uint32_t dataSize,
                                              vbsutil::xmlparser::LocatorsIterator* destination_locators_begin,
                                              vbsutil::xmlparser::LocatorsIterator* destination_locators_end) -> bool {
                return transport.send(data, dataSize, socket_, local_address_, destination_locators_begin,
                                      destination_locators_end, only_multicast_purpose_, whitelisted_, mask_len_);
            };
            order_ = order;
        }
    }
    virtual ~UDPSenderResource() {
        if (clean_up) {
            clean_up();
        }
#ifdef EDDS_XDP_TRANSPORT_COMPILE
        if (lixdp_socket_) {
            delete lixdp_socket_;
            lixdp_socket_ = nullptr;
        }
#endif
    }

    void add_locators_to_list(LocatorList& locators) const override {
        Locator locator;
#ifdef EDDS_XDP_TRANSPORT_COMPILE
        if (socket_type_ == SocketType::SOCKET_TYPE_XDP) {
            locator = dynamic_cast<LixdpSocketUDP*>(lixdp_socket_)->get_locator();
            locator.mask_len = mask_len_;
            locators.push_back(locator);
        } else
#endif
        {
            auto local_endpoint = getSocketPtr(socket_)->local_endpoint();
            transport_.endpoint_to_locator(local_endpoint, locator);
            locator.mask_len = mask_len_;
            locators.push_back(locator);
        }
    }
    bool is_whitelisted() override { return whitelisted_; }

    bool check_ip_address(const Locator& locator) const override {
        Locator sender_resource_locator;
#ifdef EDDS_XDP_TRANSPORT_COMPILE
        if (socket_type_ == SocketType::SOCKET_TYPE_XDP) {
            sender_resource_locator = dynamic_cast<LixdpSocketUDP*>(lixdp_socket_)->get_locator();
            return memcmp(&sender_resource_locator.address[12], &locator.address[12], 4) == 0;
        } else
#endif
        {
            auto local_endpoint = getSocketPtr(socket_)->local_endpoint();
            transport_.endpoint_to_locator(local_endpoint, sender_resource_locator);
            return memcmp(&sender_resource_locator.address[12], &locator.address[12], 4) == 0;
        }
    }

    static UDPSenderResource* cast(TransportInterface& transport, SenderResource* sender_resource) {
        UDPSenderResource* returned_resource = nullptr;

        if (sender_resource->kind() == transport.kind()) {
            returned_resource = dynamic_cast<UDPSenderResource*>(sender_resource);
        }

        return returned_resource;
    }

 private:
    UDPSenderResource() = delete;

    UDPSenderResource(const SenderResource&) = delete;

    UDPSenderResource& operator=(const SenderResource&) = delete;

    vbsUDPSocket socket_;
#ifdef EDDS_XDP_TRANSPORT_COMPILE
    LixdpSocket* lixdp_socket_;
    SocketType socket_type_;
#endif
    asio::ip::address local_address_;

    bool only_multicast_purpose_;
    bool whitelisted_;
    uint32_t mask_len_;

    UDPTransportInterface& transport_;
};

}  // namespace transport
}  // namespace vbs

#endif  // SRC_CPP_RTPS_TRANSPORT_UDPSENDERRESOURCE_HPP_
